package com.pmt.feedplayer.processor

import android.content.Context
import android.media.MediaExtractor
import android.media.MediaFormat
import android.media.MediaMuxer
import android.media.MediaCodec.BufferInfo as MediaBufferInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withContext
import java.io.File
import java.nio.ByteBuffer

/**
 * Android平台的视频处理器实现
 */
class AndroidVideoProcessor(private val context: Context) : VideoProcessor {
    
    override fun extractAudioAndVideo(
        videoPath: String,
        outputVideoPath: String,
        outputAudioPath: String
    ): Flow<Int> = flow {
        emit(0)
        
        withContext(Dispatchers.IO) {
            try {
                // 确保输出目录存在
                ensureOutputDirectory(outputVideoPath)
                ensureOutputDirectory(outputAudioPath)
                
                // 提取音频
                val audioProgress = extractAudioTrack(videoPath, outputAudioPath)
                emit(audioProgress)
                
                // 提取视频
                extractVideoTrack(videoPath, outputVideoPath)
                emit(100)
            } catch (e: Exception) {
                emit(-1) // 表示错误
                throw e
            }
        }
    }
    
    override fun extractAudioOnly(
        videoPath: String,
        outputAudioPath: String
    ): Flow<Int> = flow {
        emit(0)
        
        withContext(Dispatchers.IO) {
            try {
                // 确保输出目录存在
                ensureOutputDirectory(outputAudioPath)
                
                // 提取音频轨道
                val progress = extractAudioTrack(videoPath, outputAudioPath)
                emit(progress)
            } catch (e: Exception) {
                emit(-1) // 表示错误
                throw e
            }
        }
    }
    
    override fun extractVideoOnly(
        videoPath: String,
        outputVideoPath: String
    ): Flow<Int> = flow {
        emit(0)
        
        withContext(Dispatchers.IO) {
            try {
                // 确保输出目录存在
                ensureOutputDirectory(outputVideoPath)
                
                // 提取视频轨道
                extractVideoTrack(videoPath, outputVideoPath)
                emit(100)
            } catch (e: Exception) {
                emit(-1) // 表示错误
                throw e
            }
        }
    }
    
    /**
     * 提取音频轨道
     */
    private fun extractAudioTrack(videoPath: String, outputAudioPath: String): Int {
        val extractor = MediaExtractor()
        var muxer: MediaMuxer? = null
        var isMuxerStarted = false
        
        try {
            extractor.setDataSource(videoPath)
            
            // 查找音频轨道
            val audioTrackIndex = findAudioTrack(extractor)
            if (audioTrackIndex < 0) {
                throw IllegalArgumentException("No audio track found in the video")
            }
            
            // 选择音频轨道
            extractor.selectTrack(audioTrackIndex)
            
            // 获取音频格式
            val audioFormat = extractor.getTrackFormat(audioTrackIndex)
            
            // 创建MediaMuxer
            muxer = MediaMuxer(outputAudioPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
            
            // 添加音频轨道到muxer
            val muxerTrackIndex = muxer.addTrack(audioFormat)
            
            // 准备muxer
            muxer.start()
            isMuxerStarted = true
            
            // 设置缓冲区
            val bufferSize = 1024 * 1024 // 1MB缓冲区
            val buffer = ByteBuffer.allocate(bufferSize)
            val info = MediaBufferInfo()
            
            // 获取视频总时长
            val videoDuration = getVideoDuration(extractor)
            
            // 处理音频样本
            var processedDuration = 0L
            var progress = 0
            
            while (true) {
                // 读取样本数据
                val sampleSize = extractor.readSampleData(buffer, 0)
                if (sampleSize < 0) {
                    break
                }
                
                // 获取样本信息
                info.offset = 0
                info.size = sampleSize
                info.flags = extractor.sampleFlags
                info.presentationTimeUs = extractor.sampleTime
                
                // 写入样本
                muxer.writeSampleData(muxerTrackIndex, buffer, info)
                
                // 更新处理时间和计算进度
                if (videoDuration > 0) {
                    processedDuration = info.presentationTimeUs
                    val newProgress = (processedDuration * 50 / videoDuration).toInt() // 50% 进度用于音频提取
                    if (newProgress > progress) {
                        progress = newProgress
                        // 限制进度最大值为50
                        if (progress > 50) progress = 50
                    }
                }
                
                // 前进到下一个样本
                extractor.advance()
            }
            
            return progress
        } finally {
            // 释放资源，确保正确处理muxer状态
            try {
                if (muxer != null && isMuxerStarted) {
                    muxer.stop()
                    isMuxerStarted = false
                }
            } catch (e: Exception) {
                // 捕获可能的异常
            }
            try {
                muxer?.release()
            } catch (e: Exception) {
                // 捕获可能的异常
            }
            extractor.release()
        }
    }
    
    /**
     * 提取视频轨道
     */
    private fun extractVideoTrack(videoPath: String, outputVideoPath: String) {
        val extractor = MediaExtractor()
        var muxer: MediaMuxer? = null
        var isMuxerStarted = false
        
        try {
            extractor.setDataSource(videoPath)
            
            // 查找视频轨道
            val videoTrackIndex = findVideoTrack(extractor)
            if (videoTrackIndex < 0) {
                throw IllegalArgumentException("No video track found in the video")
            }
            
            // 选择视频轨道
            extractor.selectTrack(videoTrackIndex)
            
            // 获取视频格式
            val videoFormat = extractor.getTrackFormat(videoTrackIndex)
            
            // 创建MediaMuxer
            muxer = MediaMuxer(outputVideoPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
            
            // 添加视频轨道到muxer
            val muxerTrackIndex = muxer.addTrack(videoFormat)
            
            // 准备muxer
            muxer.start()
            isMuxerStarted = true
            
            // 设置缓冲区
            val bufferSize = 1024 * 1024 // 1MB缓冲区
            val buffer = ByteBuffer.allocate(bufferSize)
            val info = MediaBufferInfo()
            
            // 处理视频样本
            while (true) {
                // 读取样本数据
                val sampleSize = extractor.readSampleData(buffer, 0)
                if (sampleSize < 0) {
                    break
                }
                
                // 获取样本信息
                info.offset = 0
                info.size = sampleSize
                info.flags = extractor.sampleFlags
                info.presentationTimeUs = extractor.sampleTime
                
                // 写入样本
                muxer.writeSampleData(muxerTrackIndex, buffer, info)
                
                // 前进到下一个样本
                extractor.advance()
            }
        } finally {
            // 释放资源，确保正确处理muxer状态
            try {
                if (muxer != null && isMuxerStarted) {
                    muxer.stop()
                    isMuxerStarted = false
                }
            } catch (e: Exception) {
                // 捕获可能的异常
            }
            try {
                muxer?.release()
            } catch (e: Exception) {
                // 捕获可能的异常
            }
            extractor.release()
        }
    }
    
    /**
     * 查找音频轨道
     */
    private fun findAudioTrack(extractor: MediaExtractor): Int {
        for (i in 0 until extractor.trackCount) {
            val format = extractor.getTrackFormat(i)
            val mime = format.getString(MediaFormat.KEY_MIME)
            if (mime?.startsWith("audio/") == true) {
                return i
            }
        }
        return -1
    }
    
    /**
     * 查找视频轨道
     */
    private fun findVideoTrack(extractor: MediaExtractor): Int {
        for (i in 0 until extractor.trackCount) {
            val format = extractor.getTrackFormat(i)
            val mime = format.getString(MediaFormat.KEY_MIME)
            if (mime?.startsWith("video/") == true) {
                return i
            }
        }
        return -1
    }
    
    /**
     * 获取视频总时长
     */
    private fun getVideoDuration(extractor: MediaExtractor): Long {
        // 遍历所有轨道查找时长
        for (i in 0 until extractor.trackCount) {
            val format = extractor.getTrackFormat(i)
            if (format.containsKey(MediaFormat.KEY_DURATION)) {
                return format.getLong(MediaFormat.KEY_DURATION)
            }
        }
        return 0
    }
    
    private fun ensureOutputDirectory(filePath: String) {
        val file = File(filePath)
        val directory = file.parentFile
        if (directory != null && !directory.exists()) {
            directory.mkdirs()
        }
    }
}